<template>
    <view class="content">
        <view class="main-wrap">
            <up-form labelPosition="top" :model="state.model" :rules="state.rules" ref="formRef">
                <up-form-item label="公司中文名称" prop="info.corporateName" :labelWidth="100" borderBottom ref="item1"
                    required>
                    <up-input v-model="state.model.info.corporateName" :disabled="!state.isSave" disabledColor="#ffffff" border="none"></up-input>
                </up-form-item>
                <up-form-item label="法人代表" prop="info.legalName" :labelWidth="85" borderBottom
                    ref="item1" required>
                    <up-input v-model="state.model.info.legalName" :disabled="!state.isSave" disabledColor="#ffffff" border="none"></up-input>
                </up-form-item>
                <up-form-item label="企业执照注册号" prop="info.regNo" :labelWidth="120" borderBottom ref="item1" required>
                    <up-input v-model="state.model.info.regNo" :disabled="!state.isSave" disabledColor="#ffffff" border="none"></up-input>
                </up-form-item>
                <up-form-item label="企业执照电子照" prop="info.image" :labelWidth="120" ref="item1" required>
                    <up-upload :fileList="state.fileList" @afterRead="afterRead" :disabled="!state.isSave" :deletable="state.isSave" @delete="deletePic" name="1" multiple
                        :maxCount="1"></up-upload>
                </up-form-item>
            </up-form>
        </view>
        <view class="fixed-action-wrap">
            <view class="fixed-action-wrap-button" @click="submit">{{ state.isSave?'保存':(state.model.info.state?'审核通过':'审核中') }}</view>
        </view>
    </view>
</template>
<script setup>
const fs = uni.getFileSystemManager()
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';

const { proxy } = getCurrentInstance()
// 使用 reactive 创建响应式状态  
const state = reactive({
    isSave: true,
    showSex: false,
    fileList: [],
    model: {
        info: {
            corporateName: '',
            legalName: '',
            regNo: '',
            image: ''
        },
    },
    rules: {
        'info.corporateName': {
            type: 'string',
            required: true,
            message: '请填写公司中文名称',
            trigger: ['blur', 'change'],
        },
        'info.legalName': {
            type: 'string',
            required: true,
            message: '请填写法人代表',
            trigger: ['blur', 'change'],
        },
        'info.regNo': {
            type: 'string',
            required: true,
            message: '请填写执照注册号',
            trigger: ['blur', 'change'],
        },
        'info.image': {
            type: 'string',
            required: true,
            message: '请上传电子执照',
            trigger: ['blur', 'change'],
        },
    }
});

// 使用 ref 创建响应式引用  
const formRef = ref(null);

async function afterRead(event) {
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    let lists = [].concat(event.file);
    let fileListLen = state.fileList.length;
    lists.map((item) => {
        state.fileList.push({
            ...item,
            status: 'uploading',
            message: '上传中',
        });
    });
    for (let i = 0; i < lists.length; i++) {
        const result = await uploadFilePromise(lists[i].url);
        let item = state.fileList[fileListLen];
        state.fileList.splice(fileListLen, 1, {
            ...item,
            status: 'success',
            message: '',
            url: result,
        });
        state.model.info.image = state.fileList[0].url
        console.log(state.image)
        formRef.value.validateField('info.image');
        fileListLen++;
    }
}

function deletePic(event) {
    state.fileList.splice(event.index, 1);
}
function hideKeyboard() {
    uni.hideKeyboard()
}

function submit() {
    if (!state.isSave) {
        uni.navigateBack()
        return
    }
    // next()
    formRef.value?.validate().then(async (valid) => {
        if (valid) {
            uni.showLoading()
            //   uni.$u.toast('校验通过')
            const res = await proxy.request('/enterprise/auth/save', state.model.info, {
                method: 'POST'
            })
            if (res.code == 200) {
               setTimeout(() => {
                uni.$u.toast('保存成功')
                formRef.value?.resetFields()
                formRef.value?.clearValidate()
                uni.hideLoading()
                uni.navigateBack()
               }, 700);

            }
            console.log(res)

        } else {
            uni.$u.toast('校验失败')
        }
    }).catch(() => {
        // 处理验证错误  
        uni.$u.toast('校验失败')
    });
}

const uploadFilePromise = (url) => {
    return new Promise((resolve, reject) => {
        const base = fs.readFileSync(url, 'base64', 0)
        const basePath = 'data:image/jpeg;base64,' + base

        proxy.request('/common/file/image', { image: basePath }, {
            method: 'POST'
        }).then(res => {
            resolve(res.data.data);
        })

        // console.log(res.data.data)
        // let a = uni.uploadFile({
        //     url: 'http://106.53.65.140:8080/common/file/uploadFile', // 仅为示例，非真实的接口地址
        //     filePath: url,
        //     name: 'file',
        //     formData: {
        //         user: 'test',
        //     },
        //     success: (res) => {
        //         setTimeout(() => {
        //             resolve(res.data.data);
        //         }, 1000);
        //     },
        // });
    });
};

async function getInfo() {
    const res = await proxy.request('/enterprise/auth/get', {}, { method: 'GET' })
    if (res.data.data&&res.data.data.id) {
        state.isSave = false
        state.model.info=res.data.data
        state.fileList.push({url:state.model.info.image})
    }
}

onMounted(() => {
    getInfo()
})
</script>

<style lang="scss">
page {
    background-color: #F5F5F5;
    padding: 32rpx;
    box-sizing: border-box;
}
</style>

<style lang="scss" scoped>
.main-wrap {
    background: #FFFFFF;
    padding: 20rpx 48rpx;
    box-sizing: border-box;
    border-radius: 12rpx 12rpx 12rpx 12rpx;

    .u-content {
        padding: 32rpx;
        @include flex(column);
        align-items: center;
        justify-content: center;

        &__circle {
            background-color: $u-success;
            @include flex;
            border-radius: 100px;
            width: 60px;
            height: 60px;
            align-items: center;
            justify-content: center;
        }

        &__normal {
            font-size: 15px;
            color: $u-success;
            margin-top: 15px;
        }
    }
}

.fixed-action-wrap {
    position: fixed;
    left: 0;
    bottom: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 128rpx;
    padding: 32rpx;
    padding-bottom: env(safe-area-inset-bottom);
    box-sizing: border-box;

    &-button {
        display: flex;
        align-items: center;
        justify-content: center;
        width: calc(100% - 24px);
        height: 80rpx;
        background: #F2CB51;
        border-radius: 58rpx 58rpx 58rpx 58rpx;
    }
}
</style>